"use strict";

function initMenu($el, options) {

	var opts = $.extend({}, {
		accordeon : true
	}, options, $el.data());

	return $el.each(function() {
		var $menu = $(this);
		if ($menu.hasClass('accordion')) {
			opts.accordion = true;
		}

		var $subs = $menu.find('.sub');
		if (opts.accordion) {
			var height = 0, $sub = $();
			$subs.each(function() {
				var $this = $(this), subHeight = $this.height();
				if (subHeight > height) {
					height = subHeight;
					$sub = $this;
				}
			});

			$menu.height($menu.height());

		} else {
			$subs.show();
			$menu.height($menu.height());
			$subs.hide();
		}

		$subs.filter(function() {
			return $(this).prev().is('.open');
		}).show();

		$menu.find('li a').click($$.utils.noBubbling);
		$menu.find('li a').click(function(e) {

			var $this = $(this), $submenu = $this.next(), speed = $$.config.fxSpeed * 2 / 3;
			var $thisParent = $this.parent()

			if ($submenu.length > 0) {
				if ($thisParent.hasClass("current")) {
					return false;
				}
				$thisParent.siblings().removeClass('current');
			}
			if (opts.accordion) {
				if ($submenu.is('.sub:visible')) {

					$submenu.prev().removeClass('open');
					$submenu.prev().removeClass('current');

					$subs.filter(':visible').slideUp(speed);
					return false;

				} else if ($submenu.is('.sub:hidden')) {
					$subs.filter(':visible').slideUp(speed);
					$menu.find('.open').removeClass('open');

					$submenu.slideDown(speed);
					var pp = $submenu.prev().parent();
					pp.addClass('open');
					pp.addClass('current');
				}
			} else {
				if (!$submenu.length) {
					window.location.href = $this.attr('href');
				} else {
					$submenu.slideToggle(speed);
					$submenu.prev().toggleClass('open');
				}
				return false;
			}

		});

	});
};

